package com.wechat.page.contact.find;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.swak.fx.support.FXMLView;
import com.swak.fx.support.Window;
import com.swak.fx.support.ui.UIButton;
import com.swak.fx.support.ui.UIScrollPane;
import com.swak.fx.support.ui.UITextField;
import com.swak.ui.Event;
import com.swak.ui.EventListener;
import com.swak.utils.Lambdas;
import com.wechat.Cons;
import com.wechat.dto.ContactDTO;
import com.wechat.enums.ContactType;
import com.wechat.page.MainPage;
import com.wechat.page.api.ContactApi;
import com.wechat.page.comps.TitleFixComp;
import com.wechat.page.contact.card.ContactThumbsComp;
import com.wechat.service.node.NodeService;

import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.VPos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 * 查找好友
 * 
 * @author lifeng
 */
@FXMLView(title = "查找好友", value = "FindPage.fxml", css = "FindPage.css", stageStyle = "TRANSPARENT", singleton = false)
public class FindPage extends Window implements EventListener {

	// 标题
	private TitleFixComp titleComp;

	// 搜索框
	private StackPane searchPane;
	private GridPane searchBar;
	private UITextField searchInput;
	private UIButton searchBtn;
	private Label searchTip;

	// 结果框
	private UIScrollPane resultPane;
	private ContactThumbsComp contacts;

	// 确认框
	private StackPane confirmPane;
	private Button confirmButton;

	@Autowired
	private NodeService nodeService;
	@Autowired
	private ContactApi contactApi;

	public FindPage(Stage stage) {
		super(stage, MainPage.ADJUST_SIZE);
		this.setResizeAble(false);
		this.titleComp = this.NewComp(TitleFixComp.class);
		this.titleComp.titleProperty().set("查找好友");
		this.searchPane = new StackPane();
		this.searchBar = new GridPane();
		this.searchInput = new UITextField();
		this.searchInput.setPromptText("输入昵称、账号、关键词查找好友");
		this.searchBtn = new UIButton("搜索").Success();
		this.searchTip = new Label("推荐好友");
		this.resultPane = new UIScrollPane();
		this.contacts = this.NewComp(ContactThumbsComp.class);
		this.confirmPane = new StackPane();
		this.confirmButton = new UIButton("添加好友").Success();
	}

	@Override
	public void initializeParts() {
		super.initializeParts();
		this.initSearchPane();
		this.initResultPane();
		this.initConfirmPane();

		this.addChild(this.titleComp.getRoot());
		GridPane.setConstraints(this.titleComp.getRoot(), 0, 0);
		GridPane.setHgrow(this.titleComp.getRoot(), Priority.ALWAYS);
		GridPane.setVgrow(this.titleComp.getRoot(), Priority.NEVER);

		this.addChild(this.searchPane);
		GridPane.setConstraints(this.searchPane, 0, 1);
		GridPane.setHgrow(this.searchPane, Priority.ALWAYS);
		GridPane.setVgrow(this.searchPane, Priority.NEVER);

		this.addChild(this.resultPane);
		GridPane.setConstraints(this.resultPane, 0, 2);
		GridPane.setHgrow(this.resultPane, Priority.ALWAYS);
		GridPane.setVgrow(this.resultPane, Priority.ALWAYS);

		this.addChild(this.confirmPane);
		GridPane.setConstraints(this.confirmPane, 0, 3);
		GridPane.setHgrow(this.confirmPane, Priority.ALWAYS);
		GridPane.setVgrow(this.confirmPane, Priority.NEVER);

		GridPane.setMargin(this.titleComp.getRoot(),
				new Insets(MainPage.ADJUST_SIZE, MainPage.ADJUST_SIZE, 0, MainPage.ADJUST_SIZE));
		GridPane.setMargin(this.searchPane, new Insets(0, MainPage.ADJUST_SIZE, 0, MainPage.ADJUST_SIZE));
		GridPane.setMargin(this.resultPane, new Insets(0, MainPage.ADJUST_SIZE, 0, MainPage.ADJUST_SIZE));
		GridPane.setMargin(this.confirmPane,
				new Insets(0, MainPage.ADJUST_SIZE, MainPage.ADJUST_SIZE, MainPage.ADJUST_SIZE));
	}

	private void initSearchPane() {
		this.searchPane.getStyleClass().add("search_pane");
		this.searchBar.getStyleClass().add("search_bar");
		this.searchPane.getChildren().addAll(this.searchBar);
		this.searchBar.getChildren().addAll(this.searchInput, this.searchBtn);

		GridPane.setConstraints(this.searchBar, 0, 0);
		GridPane.setHgrow(this.searchBar, Priority.ALWAYS);
		GridPane.setVgrow(this.searchBar, Priority.ALWAYS);

		GridPane.setConstraints(this.searchTip, 0, 1);
		GridPane.setHgrow(this.searchTip, Priority.ALWAYS);
		GridPane.setVgrow(this.searchTip, Priority.NEVER);

		// searchBar
		GridPane.setConstraints(this.searchInput, 0, 0);
		GridPane.setHgrow(this.searchInput, Priority.ALWAYS);
		GridPane.setVgrow(this.searchInput, Priority.ALWAYS);
		GridPane.setHalignment(this.searchInput, HPos.CENTER);
		GridPane.setValignment(this.searchInput, VPos.CENTER);

		GridPane.setConstraints(this.searchBtn, 1, 0);
		GridPane.setHgrow(this.searchBtn, Priority.NEVER);
		GridPane.setVgrow(this.searchBtn, Priority.ALWAYS);
		GridPane.setHalignment(this.searchBtn, HPos.CENTER);
		GridPane.setValignment(this.searchBtn, VPos.CENTER);

		this.searchInput.setDisable(true);
		this.searchBtn.requestFocus();
		this.$setTimeOut(() -> {
			this.$runOnUI(() -> {
				this.searchInput.setDisable(false);
				this.searchBtn.requestFocus();
			});
		}, 100);
	}

	private void initResultPane() {
		this.contacts.selectAbleProperty().set(true);
		this.resultPane.getStyleClass().add("result_pane");
		this.resultPane.setContent(this.contacts.getRoot());
		this.resultPane.setFitToWidth(true);
		this.resultPane.setHbarPolicy(ScrollBarPolicy.NEVER);
		this.resultPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
	}

	private void initConfirmPane() {
		this.confirmPane.getStyleClass().add("confirm_pane");
		this.confirmPane.getChildren().add(this.confirmButton);
		this.confirmPane.setAlignment(Pos.CENTER_RIGHT);
	}

	@Override
	public void setupEventHandlers() {
		super.setupEventHandlers();
		this.confirmButton.addEventHandler(MouseEvent.MOUSE_CLICKED, (e) -> {
			List<ContactDTO> contacts = this.contacts.getSelective();
			this.$runContextCompleteWithUI(() -> this.contactApi.addFriends(contacts)).thenAccept(res -> {
				this.$post(Event.of().setKey(Cons.Event_Contact_Reload));
			});
		});
	}

	@Override
	public void setupBindings() {
		super.setupBindings();
		this.contacts.contactsProperty().bind(this.contactsProperty);
	}

	@Override
	public void setupValueChangedListeners() {
		super.setupValueChangedListeners();
	}

	@Override
	public void initializeFinish() {
		super.initializeFinish();
		this.layoutPageInScreenWithTopPage();
	}

	@Override
	public void windowStateChange(int state) {
		super.windowStateChange(state);
	}

	@Override
	public void close() {
		super.close();
		this.destory();
	}

	// ================================================================================
	// 异步加载数据
	// ================================================================================
	@Override
	public void mounted() {
		super.mounted();

		this.$run(() -> this.load());
	}

	private void load() {
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("[查找好友] - 准备加载数据");
		}

		// 显示查询结果
		this.nodeService.find(null).thenAccept(finds -> {
			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("[查找好友] - 查找结果: {}", finds.size());
			}

			// 转为联系人
			List<ContactDTO> contacts = Lambdas.map(finds, f -> new ContactDTO().setId(f.getId())
					.setNickName(f.getName()).setType(ContactType.User.getType()));
			this.$runOnUI(() -> {
				this.contactsProperty.addAll(contacts);
			});
		});
	}

	// ================================================================================
	// Properties
	// ================================================================================
	private final ListProperty<ContactDTO> contactsProperty = new SimpleListProperty<>(
			FXCollections.observableArrayList());

	/**
	 * 创建窗口
	 * 
	 * @return
	 */
	public static FindPage New() {
		return FindPage.New(FindPage.class, Window.createStage(false));
	}
}